package com.cn.dream_order_server.util;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.DelayQueue;

public class MyCacheUtil {
    private final DelayQueue<CacheObject> cacheQueue = new DelayQueue<CacheObject>();
    public MyCacheUtil() {
        run();
    }
    /**
     * 设置不过期的缓存
     * @param key
     * @param value
     */
    public void set(String key, Object value) {
        Map<String,Object> data = new HashMap<String, Object>();
        data.put(key, value);
        cacheQueue.add(CacheObject.buildPermanentObject(data));
    }
    /**
     * 设置带有过期时间的缓存
     * @param key
     * @param value
     * @param time
     */
    public void set(String key, Object value, long time) {
        Map<String,Object> data = new HashMap<String, Object>();
        data.put(key, value);
        cacheQueue.add(CacheObject.buildTemporaryObject(data, time));
    }
    /**
     * 获取缓存
     * @param key
     * @return null if the value is not exists
     * @exception NullPointerException: if key is null
     */
    public Object get(String key) {
        if(key == null) {
            throw new NullPointerException();
        }
        Iterator<CacheObject> iterator = cacheQueue.iterator();
        while(iterator.hasNext()) {
            CacheObject data = iterator.next();
            Map<String,Object> dataMap = data.getData();
            if(dataMap.containsKey(key)) {
                return dataMap.get(key);
            }
        }
        return null;
    }
    /**
     * 开启一个线程，一直不停地循环跑，一遇到过期的，就从队列中取出来删掉
     */
    private void run() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                while(true) {
                    try {
                        CacheObject take = cacheQueue.take();
                        Map<String, Object> data = take.getData();

                        System.out.println(take);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }


}
